package javax.per.toolkit.search;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.per.toolkit.file.FileUtil;
import javax.per.toolkit.tools.Fun;
import javax.per.toolkit.tools.Log;

import tools.Env;

public class fs {

	private static String find;
	private static List<File> fileList=new ArrayList<File>();
	private static Pattern pa;
	private static List<String> notContainType=new ArrayList<String>();
	
	static{
		notContainType.add("jar");
		notContainType.add("class");
		notContainType.add("gif");
		notContainType.add("jpg");
		notContainType.add("pdf");
	}
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		find=Fun.escapeStrForRep(Fun.getConsoleString());
		pa=Pattern.compile(find);
		String str=Env.get("FileSearchDir");
		String[] dirs=str.split(";");
		ExecutorService ser=Executors.newFixedThreadPool(3);
		for(String dir:dirs){
			loop(new File(dir),ser);
		}
		ser.shutdown();
		while(!ser.isTerminated()){
			try {
				Thread.sleep(100);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		Fun.setSeparator("\n");
		Fun.pl(fileList);
	}
	
	private static void loop(File f, ExecutorService ser){
		if(f.isDirectory()){
			for(File fs:f.listFiles()){
				loop(fs,ser);
			}
		}else{
			String ext=FileUtil.getExtension(f.getAbsolutePath());
			if(notContainType.contains(ext))
				return;
			ser.submit(new ThRun(f));
		}
	}
	
	
	
	private static class ThRun implements Runnable{

		File f;
		
		public ThRun(File file){
			this.f=file;
		}
		
		@Override
		public void run() {
			try {
				String con=FileUtil.getContent(f.getAbsolutePath());
				Matcher ma=pa.matcher(con);
				if(ma.find()){
					fileList.add(f);
					return;
				}
				
			} catch (IOException e) {
				Log.getLogger().error(f.getAbsolutePath());
				return;
			}
			
		}
		
	}

}
